package impl

import (
	"context"
	"errors"
	"wms/entity"
	"wms/glo"
	"wms/service/model"
	"wms/service/request"
	"wms/util"

	"github.com/acmestack/gorm-plus/gplus"
)

type spuService struct {
}

func NewSpuService() *spuService {
	return new(spuService)
}

var SpuSrvImpl spuService

func (s *spuService) SkuList(ctx context.Context, arg any) []*model.SimplySku {
	var entities []*entity.Sku
	_db := glo.Db_wms.Model(&entity.Sku{})
	if err := _db.Find(&entities).Error; err != nil {
		panic("sql err" + err.Error())
	}
	modelListOut := make([]*model.SimplySku, 0, len(entities))
	//
	for _, tmp := range entities {
		_w := new(model.SimplySku)
		_w.SkuID = tmp.SkuID
		_w.SkuCode = tmp.SkuCode
		modelListOut = append(modelListOut, _w)
	}
	return modelListOut
}

func (s *spuService) List(ctx context.Context, arg any) []*model.Spu {

	spus, resultDb := gplus.SelectList[entity.Spu](nil)
	if resultDb.Error != nil {
		panic("sql err" + resultDb.Error.Error())
	}

	getIds := func(l []*entity.Spu) []int64 {
		ids := make([]int64, 0, len(l))
		for i := 0; i < len(l); i++ {
			ids = append(ids, l[i].SpuID)
		}
		return ids
	}
	_ = getIds

	skuWhere := func(l []*entity.Sku, spuId int64) []*model.Sku {
		_r := make([]*model.Sku, 0)
		for i := 0; i < len(l); i++ {
			if l[i].SpuID == spuId {
				_sku := new(model.Sku)
				util.CopyStruct(_sku, l[i])
				_r = append(_r, _sku)
			}
		}
		return _r
	}

	// spuIds := getIds(spus)

	skuList, resultDb := gplus.SelectList[entity.Sku](nil)
	util.Log("skuList", skuList)
	//
	spuListOut := make([]*model.Spu, 0, len(spus))
	for _, spu := range spus {
		_spuId := spu.SpuID
		_s := new(model.Spu)
		util.CopyStruct(_s, spu)
		// 补充sku
		childSku := skuWhere(skuList, _spuId)
		_s.SkuList = childSku
		spuListOut = append(spuListOut, _s)
	}

	return spuListOut
}

func (s *spuService) Add(ctx context.Context, arg *request.AddSpuRequest) error {
	// spu := new(entity.Spu)
	// util.CopyStruct(spu, arg)

	query, u := gplus.NewQuery[entity.Spu]()
	query.Eq(&u.SpuCode, arg.SpuCode)
	spu, resultDb := gplus.SelectOne(query)
	if resultDb.RowsAffected > 0 {
		return errors.New("编码:" + arg.SpuCode + "已存在")
	}
	spu = new(entity.Spu)
	util.CopyStruct(spu, arg)
	//
	resultDb = gplus.Insert(spu)
	if resultDb.Error != nil {
		return errors.New("insert spu err:" + resultDb.Error.Error())
	}
	util.Log("spu id:", spu.SpuID)
	return nil
}
